class CategoryController < ApplicationController

def add_category
    @title = "New Category"

    if param_posted?(:category)
      @category = Category.new(params[:category])
      if @category.save 
        flash[:notice] = "Category #{@category.name} created!"
        redirect_to :action => "list_categories"
      end
    end
end

def list_categories
  @title = "Categories"

  @user = Employee.find_by_id(session[:employee_id])

  if params[:search] == nil
      @categories = Category.find(:all)
  else
      @categories = Category.search params[:search]
  end
end

  def index
    @categories = Category.find(:all)
    if request.post?
        @editing = params[:id]
    end
  end

def edit_category
  @category = Category.find_by_id(params[:id])
  @title = "Editing #{@category.name}"
  if param_posted?(:category)
      if @category.update_attributes(params[:category])
        flash[:notice] = "Category #{@category.name} updated"
        redirect_to :controller => "category", :action => "list_categories" 
      end
    end
end

  def delete_category
    if request.post?
        @category = Category.find_by_id(params[:id])
        @category.destroy
        redirect_to :action => "list_categories"
    end
  end
  
  def resolve_categories
    if not session[:categories]
       # redirect_to :action => "index"
        # find all pieces of equip with no category?
    end    
    @categoriesNoRepeats = Hash.new
    session[:categories].each do |cat|
        @categoriesNoRepeats[cat[1]] = -1
    end

    
    if request.post?
        for x in 0..@categoriesNoRepeats.size - 1 do
            cat = Category.new()
            cat.name = params[("name" + x.to_s)]
            cat.description = params[("description" + x.to_s)]
            cat.save!
            puts "adding the category   " + cat.name.to_s + "  =  " + cat.id.to_s
            @categoriesNoRepeats[cat.name] = cat.id
        end        
        session[:categories].each do |equipID|
            e = Equipment.find_by_id(equipID[0])
            if e
                e[:category] = @categoriesNoRepeats[equipID[1]]#ERROR HERE ERROR, YOU HAVE A NIL WHERE YOU DID NOT EXPECT IT.
                e.save
            end
        end     
        redirect_to(:controller => "equipment",:action => "list_all")
    else
##
##
##
    end
  
  end

private
  def param_posted?(symbol)
    request.post? and params[symbol]
  end

end
